﻿using AutoMapper;
using B.S.Data.MES.API.Dto.GenerateIDto;
using B.S.Domain.Generateplan;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.Data.MES.API.Applications.GenerateplanBasicApplication
{
    public class ShowGenerateplanBasicCommandHorter:IRequestHandler<ShowGenerateplanBasicCommand,APIPageing<List<DtoGenerateplanBasic>>>
    {
        IMapper mapper;
        IBaseRepository<GenerateplanBasic> repository;

        public ShowGenerateplanBasicCommandHorter(IMapper mapper,IBaseRepository<GenerateplanBasic> repository)
        {
            this.mapper = mapper;
            this.repository = repository;
        }

        public async Task<APIPageing<List<DtoGenerateplanBasic>>> Handle(ShowGenerateplanBasicCommand request, CancellationToken cancellationToken)
        {
            var res = new APIPageing<List<DtoGenerateplanBasic>>();

            // 使用IQueryable进行查询，不立即执行
            var query = repository.GetAll().Where(o => o.IsDel == false);
            

            // 异步获取总记录数
            res.TotalCount = await query.CountAsync(cancellationToken);
            res.Total = (int)Math.Ceiling(res.TotalCount * 1.0 / request.PageSize);

            // 异步执行分页查询
            var pagelist = await query.OrderByDescending(o => o.GenerateplanBasicId)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize).ToListAsync();

            var sou = mapper.Map<List<DtoGenerateplanBasic>>(pagelist);
            res.Data = sou;
            //res.Code = (int)RequstCode.成功;
            // res.msg = "显示成功";
            return res;
        }
    }
}
